package com.zw.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.github.pagehelper.PageHelper;

@Configuration
@EnableTransactionManagement//启用事务处理器
@MapperScan(basePackages = ShoppingMybatisConfig.DAOPACKAGE,sqlSessionFactoryRef="sqlSessionFactory")//相当于MapperScannerConfigurer
public class ShoppingMybatisConfig {
	
	public static final String DAOPACKAGE = "com.zw.dao";
	
	public static final String MAPPERPACKAGE = "classpath*:shopping/*.xml";
	
	public static final String DOMAINPACKAGE = "com.zw.entity";
	
	//数据源配置
	@Bean(name="dataSource",destroyMethod="close")
	@Primary
	@ConfigurationProperties(prefix="spring.shopping")
	public DataSource shoppingDataSource() {
		return DataSourceBuilder.create().type(org.apache.tomcat.jdbc.pool.DataSource.class).build();
	}
	
	//拦截器
	public static Interceptor interceptor() {
		Interceptor interceptor = new PageHelper();
		Properties properties = new Properties();
		properties.put("dialect","postgresql");
		properties.put("reasonable",true);
		interceptor.setProperties(properties);
		return interceptor;
	}
	
	
	
	public void setConfigurationProperties(org.apache.ibatis.session.Configuration configuration) {
		configuration.setLazyLoadingEnabled(true);
		configuration.setDefaultStatementTimeout(1000);
	}
	
	//SqlSessionFactory
	@Bean(name="sqlSessionFactory")
	@Primary
	public SqlSessionFactory crmSqlSessionFactory() throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(shoppingDataSource());
		bean.setPlugins(new Interceptor[] {interceptor()});
		bean.setTypeAliasesPackage(DOMAINPACKAGE);
		PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		bean.setMapperLocations(resolver.getResources(MAPPERPACKAGE));
		SqlSessionFactory factory = bean.getObject();
		setConfigurationProperties(factory.getConfiguration());
		return factory;
	}
	
	//事务配置
	@Bean(name="transactionManager")
	@Primary
	public PlatformTransactionManager shoppingTransactionManager() {
		return new DataSourceTransactionManager(shoppingDataSource());
	}

}
